package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryForObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper mapper;

    public void deleteByPrimaryKey(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    public void insert(Role record) {
        mapper.insert(record);
        //获取权限对象
        mapper.insert(record);
        List<Permission> permissions = record.getPermissions();
        if (permissions != null) {
            for (Permission permission : permissions) {
                //维护与权限的关系
                mapper.insertRelation(record.getId(), permission.getId());
            }
        }
    }

    public Role selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Role> selectAll() {
        return mapper.selectAll();
    }

    public void updateByPrimaryKey(Role record) {
        //删除: 破坏关系
        mapper.deleteRelation(record.getId());

        //再维护关系
        //获取权限对象
        List<Permission> permissions = record.getPermissions();
        if (permissions != null) {
            for (Permission permission : permissions) {
                //维护与权限的关系
                mapper.insertRelation(record.getId(), permission.getId());
            }
        }
        mapper.updateByPrimaryKey(record);
    }

    public PageResult query(QueryForObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Role> rows = mapper.queryForList(qo);

        return new PageResult(total, rows);
    }

    @Override
    public List<Long> getRoleIdByEmpId(Long empId) {
        return mapper.getRoleIdByEmpId(empId);
    }

    //用于权限校验
    public Set<String> selectRoleByEmployeeId(Long empId) {
        return mapper.selectRoleByEmployeeId(empId);
    }

    @Override
    public List<String> queryRoleSnByEmpId(Long id) {
        return mapper.queryRoleSnByEmpId(id);
    }
}